package simorg.domain;

import java.util.Collection;

import org.dom4j.Element;

import simorg.domain.persistence.AssignmentTable;
import simorg.domain.persistence.StudentCourseJoinTable;
import simorg.domain.persistence.UserTable;
import simorg.util.DatabaseConnection;
import simorg.util.StringUtil;

public class Course {

	private int id;
	private String name;
	private String semester;
	private String section;
	private int instructorID;
	
	private User instructor; // lazy load
	
	
	public Course() {
		id = -1;
	}
	
	public void buildDomainXml(Element root, DatabaseConnection dc) {
		Element course = root.addElement("course");
		course.addAttribute("id", String.valueOf(this.getId()));
		Element name = course.addElement("name");
		name.setText(StringUtil.nullSafe(this.getName()));
		Element semester = course.addElement("semester");
		semester.setText(StringUtil.nullSafe(this.getSemester()));
		Element section = course.addElement("section");
		section.setText(StringUtil.nullSafe(this.getSection()));
		if ( this.getInstructor(dc) != null ) {
			this.getInstructor(dc).buildDomainXml(course);
		}
		Element assignments = course.addElement("assignments");
		for ( Assignment a : this.getAssignments(dc)) {
			a.buildDomainXml(assignments, dc);
		}
		
		Element students = course.addElement("students");
		for ( Integer studentId : StudentCourseJoinTable.getUserIds(dc, this.getId())) {
			User student = UserTable.findById(dc, studentId);
			student.buildDomainXml(students);
		}
		
		return;
	}
	
	public Collection<Assignment> getAssignments(DatabaseConnection dc) {
		return AssignmentTable.findByCourseId(dc, this.getId());
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getSemester() {
		return semester;
	}

	public void setSemester(String semester) {
		this.semester = semester;
	}

	public String getSection() {
		return section;
	}

	public void setSection(String section) {
		this.section = section;
	}

	public int getInstructorID() {
		return instructorID;
	}

	public void setInstructorID(int instructorID) {
		this.instructorID = instructorID;
		this.instructor = null; // will be loaded when asked for
	}

	public User getInstructor(DatabaseConnection dc) {
		if ( instructor == null ) {
			instructor = UserTable.findById(dc, this.instructorID);
		}
		return instructor;
	}

	
	
	
}
